package gvo.newSearch;

import java.awt.BorderLayout;
import java.awt.Dimension;

import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JScrollPane;
import javax.swing.JSplitPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.JTextPane;
import javax.swing.ListSelectionModel;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.event.TableModelEvent;
import javax.swing.event.TableModelListener;
import javax.swing.text.BadLocationException;
import javax.swing.text.Style;
import javax.swing.text.StyleConstants;
import javax.swing.text.StyledDocument;

import ca.odell.glazedlists.BasicEventList;
import ca.odell.glazedlists.EventList;
import ca.odell.glazedlists.FilterList;
import ca.odell.glazedlists.SortedList;
import ca.odell.glazedlists.matchers.TextMatcherEditor;
import ca.odell.glazedlists.swing.EventListModel;
import ca.odell.glazedlists.swing.EventTableModel;
import ca.odell.glazedlists.swing.TableComparatorChooser;
import ca.odell.glazedlists.swing.TextComponentMatcherEditor;

public class BiblioTune extends JFrame implements ListSelectionListener, TableModelListener {
	
	private FilterList<GlazedGVOall> filteredFinal;
	private EventList<String> autorenEL;
	private static final String AUTORENLISTE = "Autor";
	private static final String STICHWORTLISTE = "Stichwort";
	private TextMatcherEditor<GlazedGVOall> autFilt, keyFilt;
	private JList keyList, autorenList;
	private Style styleTest;
	private Style styleBold, styleItalic, styleNorm;
	private StyledDocument pad;
	private JTable allTable;
	private EventTableModel<GlazedGVOall> allTableModel;
	private GlazedGVOall store;
	//private boolean isAdjusting = false;

	public BiblioTune(EventList<GlazedGVOall> allEL) {
		this.setTitle("Bibliothek");
		this.getContentPane().setLayout(new BorderLayout());

		// Allgemein
		
		SortedList<GlazedGVOall> allSortedEL = new SortedList<GlazedGVOall>(allEL,
				new BuchComparator());
		Dimension minimumSize = new Dimension(100, 50);

		// Autoren
		autorenEL = new BasicEventList<String>();

		// gvostore.sqlTool.loadAutoren(autorenEL);
		AutorenFromEL.getAutoren(allSortedEL, autorenEL);
		EventListModel<String> autorenListModel = new EventListModel<String>(autorenEL);
		autorenList = new JList(autorenListModel);
		autorenList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
		autorenList.addListSelectionListener(this);
		autorenList.setName(AUTORENLISTE);
		JScrollPane autorenSP = new JScrollPane(autorenList);
		autorenSP.setMinimumSize(minimumSize);

		// Stichworte
		EventList<String> keyEL = new BasicEventList<String>();
		KeyFromEL.getKeys(allSortedEL, keyEL);
		//sqlTool.loadStichworte(keyEL);
		EventListModel<String> keyListModel = new EventListModel<String>(keyEL);
		keyList = new JList(keyListModel);
		keyList.addListSelectionListener(this);
		keyList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
		keyList.setName(STICHWORTLISTE);
		JScrollPane keySP = new JScrollPane(keyList);
		keySP.setMinimumSize(minimumSize);

		// Ober SplitTeil
		JSplitPane top = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, autorenSP, keySP);
		top.setOneTouchExpandable(true);
		top.setDividerLocation(300);
		top.setPreferredSize(new Dimension(400, 200));
		// top.setBorder(null);
		top.setMinimumSize(new Dimension(100, 100));

		// JTextField
		JTextField filterTF = new JTextField(10);
		autFilt = new TextMatcherEditor<GlazedGVOall>(new AutorenFilterator());
		FilterList<GlazedGVOall> filteredAutor = new FilterList<GlazedGVOall>(allSortedEL, autFilt);
		keyFilt = new TextMatcherEditor<GlazedGVOall>(new KeyFilterator());
		FilterList<GlazedGVOall> filteredKey = new FilterList<GlazedGVOall>(filteredAutor, keyFilt);
		filteredFinal = new FilterList<GlazedGVOall>(
				filteredKey,
				new TextComponentMatcherEditor<GlazedGVOall>(filterTF, new GlazedGVOallFilterator()));
		
		getContentPane().add(filterTF, BorderLayout.NORTH);
		// Tabelle
		allTableModel = new EventTableModel<GlazedGVOall>(filteredFinal, new GlazedGVOallTableFormat());
		allTableModel.addTableModelListener(this);
		allTable = new JTable(allTableModel);
		SelectionListener listener = new SelectionListener();
		allTable.getSelectionModel().addListSelectionListener(listener);
		allTable.getColumnModel().getSelectionModel().addListSelectionListener(listener);
		@SuppressWarnings("unused")
		TableComparatorChooser<GlazedGVOall> tableSorter = TableComparatorChooser.install(allTable,
			allSortedEL, TableComparatorChooser.MULTIPLE_COLUMN_MOUSE);
		JScrollPane allTableSP = new JScrollPane(allTable);
		allTableSP.setMinimumSize(new Dimension(300, 150));
		// Unterer SplitTeil
		JSplitPane splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT, top, allTableSP);
		splitPane.setOneTouchExpandable(true);
		splitPane.setDividerLocation(200);

		// Add the split pane to this frame
		getContentPane().add(splitPane, BorderLayout.CENTER);
		
		JTextPane textPane = new JTextPane();
		pad = textPane.getStyledDocument();
		
		JScrollPane txtSP = new JScrollPane(textPane);
		txtSP.setPreferredSize(new Dimension(150, 600));
		getContentPane().add(txtSP, BorderLayout.EAST);
		
		addStyles();
		allTable.addRowSelectionInterval(0, 0);
		
		
       
        
		
		this.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
		this.setSize(700, 700);
		// Display the window.
		// this.pack();
		this.setVisible(true);
	}
	public void clearPad(){
		try {
			pad.remove(0, pad.getLength());
		} catch (BadLocationException e) {
			e.printStackTrace();
		}
	}
	public void appendToPad(Style style, String text){
		//System.out.println(">"+text+"<");
		 // Append to document
        try {
			pad.insertString(pad.getLength(), text, style);
		} catch (BadLocationException e) {
			e.printStackTrace();
		}
	}
	public void addStyles(){
		// Create a style object and then set the style attributes
		styleTest = pad.addStyle("StyleName", null);
    
        // Italic
        StyleConstants.setItalic(styleTest, true);
    
        // Bold
        StyleConstants.setBold(styleTest, true);
    
        // Font family
        StyleConstants.setFontFamily(styleTest, "SansSerif");
    
        // Font size
        StyleConstants.setFontSize(styleTest, 11);
    
        // Background color
        //StyleConstants.setBackground(style, Color.blue);
    
        // Foreground color
        //StyleConstants.setForeground(style, Color.white);
        styleNorm = pad.addStyle("normal", null);
        StyleConstants.setItalic(styleNorm, false);
        StyleConstants.setBold(styleNorm, false);
        StyleConstants.setFontFamily(styleNorm, "SansSerif");
        StyleConstants.setFontSize(styleNorm, 11);
        
        styleItalic = pad.addStyle("italic", null);
        StyleConstants.setItalic(styleItalic, true);
        StyleConstants.setBold(styleItalic, false);
        StyleConstants.setFontFamily(styleItalic, "SansSerif");
        StyleConstants.setFontSize(styleItalic, 11);
        
        styleBold = pad.addStyle("bold", null);
        StyleConstants.setItalic(styleBold, false);
        StyleConstants.setBold(styleBold, true);
        StyleConstants.setFontFamily(styleBold, "SansSerif");
        StyleConstants.setFontSize(styleBold, 11);
	}
	public static String prepString(String in){
		if(in==null)
			return "";
		int last = in.length()-1;
		try {
			if (last==-1)
				return in;
			while (true){
				if(in.charAt(last)=='\n' || in.charAt(last)==' '){
					if(last==0){
						break;
					}
					last--;
				} else {
					break;
				}
				
			}
		} catch (StringIndexOutOfBoundsException e) {
			System.out.println("FEHLER:>"+in+"<");
			e.printStackTrace();
			
		}
		return in.substring(0, last+1);
	}
	public void pasteGlazedGVOall(GlazedGVOall in){
		if(in.equals(store)){
			//System.out.println("Same");
			return;
		}
		//System.out.println("New");
		store = in;
		clearPad();
		appendToPad(styleBold, "Signatur: ");
		appendToPad(styleNorm, prepString(in.getSignatur()));
		appendToPad(styleNorm, "\n");
		appendToPad(styleBold, "Titel: ");
		appendToPad(styleNorm, prepString(in.getTitel()));
		appendToPad(styleNorm, "\n");
		appendToPad(styleBold, "Verfasser: ");
		appendToPad(styleNorm, prepString(in.getAutoren()));
		appendToPad(styleNorm, "\n");
		appendToPad(styleBold, "Stichworte: ");
		appendToPad(styleNorm, prepString(in.getStichworte()));
		appendToPad(styleNorm, "\n");
		appendToPad(styleBold, "Anmerkung: ");
		appendToPad(styleNorm, prepString(in.getAnmerkung()));
		appendToPad(styleNorm, "\n");
		appendToPad(styleBold, "AusgabeVersion: ");
		appendToPad(styleNorm, prepString(in.getAusgabeVersion()));
		appendToPad(styleNorm, "\n");
		appendToPad(styleBold, "ISBNPreis: ");
		appendToPad(styleNorm, prepString(in.getIsbnPreis()));
		appendToPad(styleNorm, "\n");
		appendToPad(styleBold, "Kollation: ");
		appendToPad(styleNorm, prepString(in.getKollation()));
		appendToPad(styleNorm, "\n");
		appendToPad(styleBold, "Notiz: ");
		appendToPad(styleNorm, prepString(in.getNotiz()));
		appendToPad(styleNorm, "\n");
		appendToPad(styleBold, "OrtJahr: ");
		appendToPad(styleNorm, prepString(in.getOrtJahr()));
		appendToPad(styleNorm, "\n");
		appendToPad(styleBold, "Reihe: ");
		appendToPad(styleNorm, prepString(in.getReihe()));
		appendToPad(styleNorm, "\n");
		appendToPad(styleBold, "Reronr: ");
		appendToPad(styleNorm, prepString(in.getReroNr()));
		appendToPad(styleNorm, "\n");
		
	}
	public void valueChanged(ListSelectionEvent e) {
		if (e.getValueIsAdjusting()){
			return;
		}
		
		JList tmp = (JList) e.getSource();
		if (AUTORENLISTE.equals(tmp.getName())) {

			//System.out.println("AutorenList changed "+tmp.getName()+"/" + tmp.getSelectedIndex());
			String[] res;
			if (tmp.getSelectedIndex() == 0) {
				res = new String[1];
				res[0] = "";
				
			} else {
				Object[] o = autorenList.getSelectedValues();
				int len = o.length;
				if (len == 0) {
					res = new String[1];
					res[0] = "";
				} else {
					res = new String[1];
					res[0] = (String) o[0];

				}
				
			}
			
			autFilt.setFilterText(res);
			
			
		} else if (STICHWORTLISTE.equals(tmp.getName())) {
			//System.out.println("StichwortList changed");
			String[] res;
			if (tmp.getSelectedIndex() == 0) {
				res = new String[1];
				res[0] = "";
				keyFilt.setFilterText(res);
			} else {
				Object[] o = keyList.getSelectedValues();
				int len = o.length;
				if (len == 0) {
					res = new String[1];
					res[0] = "";
				} else {
					res = new String[1];
					res[0] = (String) o[0];

				}
				
				keyFilt.setFilterText(res);
				
			}
		}
	}
	public GlazedGVOall getValue(int id){
		for(GlazedGVOall res: filteredFinal){
			if(res.getIdBuch()==id){
				return res;
			}
		}
		return null;
	}
	
	 private class SelectionListener implements ListSelectionListener {
		

		
		SelectionListener() {
			
		}

		public void valueChanged(ListSelectionEvent e) {
			if (e.getValueIsAdjusting()) {
                // The mouse button has not yet been released
				//System.out.println("TableEvent VA");
				return;
            }
			
			// If cell selection is enabled, both row and column change events are fired
            if (e.getSource() == allTable.getSelectionModel()
                  && allTable.getRowSelectionAllowed()) {
                // Column selection changed
               
                int ind = allTable.getSelectedRow();
                if(ind==-1){
                	return;
                }
                int anzRow = allTable.getRowCount();
                if(anzRow==0){
                	return;
                }
                if(anzRow<=ind){
                	//System.out.println("Fehler abgefangen!!");
                	//allTable.removeRowSelectionInterval(0, anzRow-1);
                	//allTable.addRowSelectionInterval(0, 0);
                	return;
                }
               
                int id = (Integer)allTable.getValueAt(ind, 0);
                GlazedGVOall res = getValue(id);
                if(res==null){
                	return;
                }
                
                pasteGlazedGVOall(res);
               
                
                
                
            } else if (e.getSource() == allTable.getColumnModel().getSelectionModel()
                   && allTable.getColumnSelectionAllowed() ){
                // Row selection changed
               
               
            }
    
            
		}

	}
	public void tableChanged(TableModelEvent e) {
		
		int anzRow = allTable.getRowCount();
		if(anzRow==0){
			return;
		}
		/*
		String type;
		switch(e.getType()){
		case TableModelEvent.DELETE:
			type = "Delete";
			break;
		case TableModelEvent.INSERT:
			type = "Insert";
			break;
		case TableModelEvent.UPDATE:
			type = "Update";
			break;
		default:
			type = "Unbekannt";
		}
		int ind = allTable.getSelectedRow();
		
		int id;
		if(ind == -1){
			id = -1;
		} else {
			id = (Integer)allTable.getValueAt(ind, 0);
		}
		 */
		//System.out.println("Typ "+type +" id:" +id+" SR:"+ind+" SRC:" +allTable.getSelectedRowCount() +" AR:" + anzRow);
		
		if(allTable.getSelectedRow()==0 && allTable.getSelectedRowCount() ==1 ){
			return;
		}
		
		//System.out.println("TME Here!! " );
		allTable.removeRowSelectionInterval(0, anzRow-1);
    	allTable.addRowSelectionInterval(0, 0);
		
	}
	

}
